# -*- coding: utf-8 -*-
"""
@Time : 2024/2/24 10:13
@Author : ChenXiaoliang
@Email : middlegod@sina.com
@File : stock_snapshot.py
@Desc : 对每只股票的日线进行拍照
"""

from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.chrome.options import Options
import time
import logging

from get_stocks import get_stocks

LOG_FORMAT = "%(levelname)s %(asctime)s - %(message)s"
logging.basicConfig(filename='stock_snapshot.log', level=logging.INFO, filemode='a', format=LOG_FORMAT)
logger = logging.getLogger()

# linux webdriver路径
# driver_path = "/usr/bin/chromedriver"


# Windows webdriver路径
driver_path = "D:\webdriver\chromedriver.exe"

# 是否设置为无头模式
head_less = True
if head_less:
    chrome_options = Options()
    chrome_options.add_argument("--headless")
    chrome_options.add_argument("--no-sandbox")
    driver = webdriver.Chrome(driver_path, chrome_options=chrome_options)
else:
    driver = webdriver.Chrome(driver_path)

stocks = get_stocks()
for stock in stocks:
    driver.maximize_window()
    driver.get(f"https://xueqiu.com/S/{stock['code']}")

    # 关闭掉登录提示窗
    login_win = driver.find_element_by_class_name("modal__login")
    action = ActionChains(driver)
    action.move_to_element(login_win).perform()
    close = login_win.find_element_by_class_name('close')
    driver.execute_script('arguments[0].click();', close)
    # close.click()

    # login_win.click()
    # print(login_win, login_win.text, 1024)
    # time.sleep(5)
    # text = login_win.find_element_by_class_name("iconfont")
    # print(text)
    # driver.execute_script('arguments[0].click();', text)
    # time.sleep(5)

    # 切换日线
    chart_period_ls = driver.find_elements_by_class_name("chart-period-list")
    for chart in chart_period_ls:
        if chart.text.strip() == "日K":
            # chart.click()
            driver.execute_script('arguments[0].click();', chart)
            time.sleep(0.6)
    driver.set_window_size(1200, 820)
    driver.get_screenshot_as_file(f"{stock['name']}.png")
    logger.info(f"{stock['name']}日线走势图片保存成功")
